package com.chenyi.framework.security.handle;

import com.alibaba.fastjson.JSON;
import com.chenyi.common.constant.Constants;
import com.chenyi.common.core.domain.ApiError;
import com.chenyi.common.core.domain.model.LoginAdmin;
import com.chenyi.common.exception.BadRequestException;
import com.chenyi.common.utils.AdminUtils;
import com.chenyi.common.utils.ServletUtils;
import com.chenyi.common.utils.StringUtils;
import com.chenyi.framework.web.service.AdminTokenService;
import com.chenyi.system.domain.SysAdminLogin;
import com.chenyi.system.service.ISysAdminLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;

/**
 * 认证失败处理类 返回未授权
 * 
 * @author wangkh
 */
@Component
public class AdminAuthenticationEntryPointImpl implements AuthenticationEntryPoint, Serializable
{
    private static final long serialVersionUID = -8970718410437077606L;

    @Autowired
    private AdminTokenService tokenService;

    @Autowired
    private ISysAdminLoginService adminLoginService;

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException)
            throws IOException
    {
        // 当用户尝试访问安全的REST资源而不提供任何凭据时，将调用此方法发送401 响应
        String msg = StringUtils.format("请求访问：{}，认证失败，无法访问系统资源", request.getRequestURI());
        response.setContentType("text/html;charset=UTF-8");
        String token = null;
        if (StringUtils.isNotEmpty(token = tokenService.getToken(request))){
            SysAdminLogin sysAdminLogin = adminLoginService.selectAdminLoginByToken(tokenService.getJwtToken(token), Constants.LOGIN_FAIL);
            if (sysAdminLogin == null){
                response.sendError(HttpStatus.UNAUTHORIZED.value(),"登录状态已过期，您可以继续留在该页面，或者重新登录");
            }else{
                response.sendError(HttpStatus.UNAUTHORIZED.value(),sysAdminLogin.getMsg());
            }
        }else{
            response.sendError(HttpStatus.UNAUTHORIZED.value(),msg);
        }
    }
}
